﻿#include "DataManger.h"
#include "DBService.h"
#include "DataPackage.h"
#include "OutPutMessage.h"

#include <QDateTime>

#include <QSqlQuery>
#include <QSqlError>
#include <QVariantList>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>

DataManger::DataManger(QDBService * db, QObject *parent)
	: QObject(parent)
{
	pDbService = db;
}

DataManger::~DataManger()
{

}

QJsonObject DataManger::requestData(const QString & method, const QByteArray & request)
{
	if (method =="/select")
	{
#ifdef Q_OS_WIN
		return select(request);
#else
		const QString & strSQL = QString::fromLatin1(request);
		return select(strSQL);

#endif // Q_OS_WIN
	}

	if (method == "/update" || method == "/insert" || method == "/delete" )
	{
#ifdef Q_OS_WIN
		return execSQL(request);
#else
		const QString & strSQL = QString::fromLatin1(request);
		return execSQL(strSQL);
#endif

	}

	if (method == "/execBatch")
	{
		QJsonObject error;

#ifdef Q_OS_WIN
		const QJsonDocument & doc = QJsonDocument::fromJson(request);
#else
		const QString & strDoc =  QString::fromLatin1(request);
		const QJsonDocument & doc = QJsonDocument::fromJson(strDoc.toUtf8());
#endif // Q_OS_WIN

		if (doc.isObject())
		{
			const QJsonObject & obj = doc.object();
			const QJsonValue & value = obj.value("sql");

			if (value.isArray())
			{
				const QJsonArray & arr = value.toArray();
				const QVariantList & listSQL = arr.toVariantList();
				
				if (listSQL.count() == 0)
				{
					QString strError = tr("Not Found Sql in Json");
					error.insert("Error", strError);
					outPutMessage(strError, MSG_ERROR);
					return error;
				}
				else if (listSQL.count() == 1)
				{
					return execSQL(listSQL.at(0).toString());
				}
				else
				{
					return execBatch(listSQL);
				}
			}
		}

		QString strError = tr("Json is not a Object or a Array!");
		outPutMessage(strError, MSG_ERROR);
		error.insert("Error", strError);
		return error;
	}

    if (method =="/getTime")
    {
        const QDateTime & dtTime = QDateTime::currentDateTime();
        QString strTime = dtTime.toString("yyyy-MM-dd hh:mm:ss");
        QJsonObject resObj;
        resObj.insert("time", strTime);
        return resObj;
    }

	return QJsonObject();
}

QJsonObject DataManger::select(const QString & SQL)
{
	QJsonObject record;
	DataPackage pack;

	bool bExec = false;
	QSqlQuery * query = pDbService->select(SQL, bExec);
	if (bExec && query)
	{
		if (!pack.response(*query, record))
		{
            const QString & strError = pack.getError();
			QString strErrors = tr("Serialize Data Failed, Error: %1").arg(strError);
			pack.response(strError, true, record);
			outPutMessage(strErrors, MSG_ERROR);
		}
		else
		{
			QString strInfo = tr("Select Data: %1").arg(SQL);
			outPutMessage(strInfo);
		}

		delete query;
		query = NULL;
		return record;
	}

	if (query)
	{
		QString strError = tr("Select Data Failed! \nSQL: %1 \n Error: %2").arg(SQL).arg(query->lastError().text());
		outPutMessage(strError, MSG_ERROR);
		delete query;
		query = NULL;
		pack.response(strError, true, record);
	}
	else
	{
		QString strError = tr("Connect DB Failed!");
		outPutMessage(strError, MSG_ERROR);
		pack.response(strError, true, record);
	}

	return record;
}

QJsonObject DataManger::execSQL(const QString & SQL)
{
	QString strMsg;
	bool bExec = pDbService->execSQL(SQL, strMsg);

	QJsonObject reslut;
	if (bExec)
	{
		reslut.insert("Success", strMsg);
	}
	else
	{
		reslut.insert("Error", strMsg);
	}

	return reslut;
}

QJsonObject DataManger::execBatch(const QVariantList & SQL)
{
	QString strMsg;
	bool bExec = pDbService->execBatch(SQL, strMsg);

	QJsonObject reslut;
	if (bExec)
	{
		reslut.insert("Success", strMsg);
	}
	else
	{
		reslut.insert("Error", strMsg);
	}

	return reslut;
}
